
import { DatePicker, Form, Input, InputNumber, Radio, Select } from "antd"
import { useEffect, useState } from "react"
import { Outlet, useLocation, useNavigate } from "react-router-dom"
import { $eventBus } from "../../../../common/utils"
import HomePage_DrawerComponent from "../../../../components/drawer"
import modalCloseImage from "../../../../assets/image/icon_line_close2@2x.png"
import lessModule from "./index.module.less"
import HomePage_ModalComponent from "../../../../components/modal"
import Tree, { DataNode, TreeProps } from "antd/es/tree"
import dayjs from "dayjs"
import { $Http } from "../../../../network"
const { RangePicker } = DatePicker;
// 主页-数据管理页面-头部菜单tab组件
const HomePage_DataManagementPage_HeaderMenuTabComponent: React.FC = () => {
    const navigate = useNavigate();
    const tabList = [
        {
            name: "站点台账",
            routerName: "siteAccount",
        },
        {
            name: "历史曲线",
            routerName: "historicalCurve",
        },
        {
            name: "事件统计",
            routerName: "eventStatistics",
        },
        {
            name: "录波数据",
            routerName: "recordingData",
        },
        {
            name: "数据导出",
            routerName: "dataExport",
        },
    ]
    const [tabName, setTabName] = useState<string>(tabList[0].name)
    const locationData = useLocation()

    const init_tabName = () => {
        setTabName(tabList.find((item) => !locationData.pathname.split("/")[3] || item.routerName === locationData.pathname.split("/")[3])?.name ?? "")

    }
    const click_tab = (tabData: object) => {
        setTabName(tabData["name"])
        navigate(`/home/dataManagement/${tabData["routerName"]}`)
    }

    useEffect(() => {
        init_tabName()
    }, [])
    return (
        <div className={`${lessModule["homePageDataManagementPage-headerMenu__homePageDataManagementPageHeaderMenuTabComponent"]}`}>
            {
                tabList.map((item, idx) => {
                    return (
                        <div className={`${lessModule["headerMenu-homePageDataManagementPageHeaderMenuTabComponent__tabItem"]}`}
                            style={{
                                color: tabName === item.name ? "#FFFFFF" : "#B8D6E6",
                                backgroundColor: tabName === item.name ? "rgba(23,161,230,0.5)" : "rgba(23,161,230,0.1)",
                                borderColor: tabName === item.name ? "#17A1E6" : "rgba(23,161,230,0.3)",
                                borderWidth: tabName === item.name ? "0 0 1px 0" : "1px"
                            }}
                            key={'tabList' + idx}
                            onClick={() => click_tab(item)}>{item.name}</div>
                    )
                })
            }
        </div>
    )
}

// 主页-数据管理页面-头部菜单查询组件-抽屉内容组件
interface homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponentPropsInterface {
    get_isDrawerClose: Function
}
const HomePage_DataManagementPage_HeaderMenuSearchComponent_DrawerContentComponent: React.FC<homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponentPropsInterface> = (props) => {
    const [form] = Form.useForm()
    const initialValuesData = {
        site: null,
        account: null,
        indexType: null,
        dateRange: null,
        fileName: null
    }
    const formItemList = [
        {
            name: "site",
            label: "站点",
            rules: [{ required: true, message: '请选择' }],
            type: "selectOptGroup",
        },
        {
            name: "account",
            label: "监测点",
            rules: [{ required: true, message: '请选择' }],
            type: "select",
            option: [{ name: "1#进线A" },]
        },
        {
            name: "indexType",
            label: "指标类型",
            rules: [{ required: true, message: '请选择' }],
            type: "select",
            option: [{ name: "有功功率" },]
        },
        {
            name: "dateRange",
            label: "时间范围",
            rules: [{ required: true, message: '请选择' }],
            type: "rangePicker",
        },
        {
            name: "fileName",
            label: "文件名",
            rules: [{ required: false, message: '请输入' }],
            type: "input",
        },
    ]
    const change_date = (date: any, dateString: Array<string>) => {

    }
    const click_closeDrawer = () => {
        props.get_isDrawerClose(false)
    }

    const click_submitDrawer = () => {
        form.validateFields().then(() => {
            console.log(4444);


        })

    }
    return (
        <div className={`${lessModule["headerMenu-homePageDataManagementPageHeaderMenuSearchComponent__homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponent"]}`}>
            <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponent-homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponent__header"]}`}>
                <span>新建导出数据</span>
                <img className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponent-header__closeImage"]}`} src={modalCloseImage} onClick={() => click_closeDrawer()} />
            </div>
            <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponent-homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponent__main"]}`}>
                <Form
                    form={form}
                    initialValues={initialValuesData}
                >
                    <>
                        {
                            formItemList.map((item, idx) => {
                                return (

                                    <Form.Item
                                        className={`${lessModule["main-homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponentBasicInformationComponent__formItem"]}`}
                                        key={"formItemList" + idx}
                                        labelCol={{ span: 24 }}
                                        name={item["name"]}
                                        label={`${item["label"]}：：`}
                                        rules={item["rules"]}
                                    >
                                        {
                                            item["type"] === "selectOptGroup" ? <Select
                                                placeholder="请选择"
                                                optionLabelProp="labelProp"
                                                options={JSON.parse(sessionStorage.homePage_freewayList)}
                                                fieldNames={{ value: "labelProp" }}
                                            />
                                                : item["type"] === "select" ? <Select
                                                    placeholder="请选择"
                                                    options={item["option"]}
                                                    fieldNames={{ label: "name", value: "name" }}
                                                />
                                                    : item["type"] === "rangePicker" ? <RangePicker allowClear={false} separator={<span className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponentBasicInformationComponent-formItem__rangePickerSeparator"]}`}>至</span>} onChange={change_date} />
                                                        : item["type"] === "input" && <Input placeholder="请输入" autoComplete="off" />
                                        }

                                    </Form.Item>
                                )
                            })
                        }
                    </>
                </Form>
            </div>
            <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponent-homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponent__footer"]}`}>
                <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponent-footer__btn"]} ${lessModule["homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponent-footer__btnCancel"]}`} onClick={() => click_closeDrawer()}>取消</div>
                <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponent-footer__btn"]} ${lessModule["homePageDataManagementPageHeaderMenuSearchComponentDrawerContentComponent-footer__btnSubmit"]}`} onClick={() => click_submitDrawer()}>确定</div>
            </div>
        </div>
    )
}
// 主页-数据管理页面-头部菜单查询组件-弹窗内容组件
interface homePageDataManagementPageHeaderMenuSearchComponentModalContentComponentPropsInterface {
    get_isModalClose: Function
}
const HomePage_DataManagementPage_HeaderMenuSearchComponent_ModalContentComponent: React.FC<homePageDataManagementPageHeaderMenuSearchComponentModalContentComponentPropsInterface> = (props) => {

    const [tabName, setTabName] = useState<string>("立即录波")
    let [step, setStep] = useState<number>(0)
    const [treeList, setTreeList] = useState<Array<DataNode>>([])
    let [selectedList, setSelectedList] = useState<Array<any>>([])
    let [startTime, setStartTime] = useState<string>()
    let duration: number

    const click_tab = (value: string) => {
        setTabName(value)
        setStep(0)
    }

    const recurrence_treeList = (list: Array<any>, level: number, parentKey: string) => {
        list.forEach((item) => {
            item["checkable"] = level > 2
            item["key"] = `${parentKey}${parentKey ? "%@)" : ""}${item["title"]}`
            item["children"] && recurrence_treeList(item["children"], level + 1, item["key"])
        })
        setTreeList(list)

    }

    const check_tree: TreeProps['onCheck'] = (checkedKeys, info) => {
        selectedList = Array.isArray(checkedKeys) ? checkedKeys.filter((item) => item.toString().split("%@)").length === 5) : []
        setSelectedList(selectedList)
    }
    const click_tagClear = (idx: number) => {
        selectedList.splice(0, 1)
        setSelectedList([...selectedList])
    }

    const change_startTime = (date: any, dateStr: string) => {
        console.log(date, dateStr);

    }
    const change_duration = (event: object) => {
        duration = event["target"]["value"]

    }
    const click_closeModal = () => {
        props.get_isModalClose(false)
    }
    const click_lastStep = () => {
        setStep(0)
    }
    const click_submitModal = () => {

    }
    const click_nextStep = () => {
        setStep(1)


    }
    useEffect(() => {
        recurrence_treeList([
            {
                title: 'parent 1',
                children: [
                    {
                        title: 'parent 1-1',
                        children: [
                            {
                                title: 'leaf1',
                                children: [
                                    {
                                        title: 'leaf2',
                                        children: [
                                            {
                                                title: 'leaf23',
                                            },
                                        ],
                                    },
                                ],
                            },
                            {
                                title: 'leaf4',
                                children: [
                                    {
                                        title: 'leaf5',
                                        children: [
                                            {
                                                title: 'leaf27',
                                            },
                                            {
                                                title: 'leaf28',
                                            },
                                        ],
                                    },
                                ],
                            },
                        ],
                    },
                ],
            },
        ], 0, "")
    }, [])
    return (
        <div className={`${lessModule["headerMenu-homePageDataManagementPageHeaderMenuSearchComponent__homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent"]}`}>
            <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponent-homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent__header"]}`}>
                <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-header__tab"]}`}>
                    <div className={`${lessModule["header-tab__btn"]}`} style={{ color: tabName === "立即录波" ? "#FFFFFF" : "#B8D6E6", backgroundColor: tabName === "立即录波" ? "rgba(23,161,230,0.5)" : "rgba(23,161,230,0.1)", borderWidth: tabName === "立即录波" ? "0 0 1px 0" : "1px", borderColor: tabName === "立即录波" ? "#17A1E6" : "rgba(23,161,230,0.3)", padding: tabName === "立即录波" ? "10px 8px 10px 7px" : "10px 7px 10px 8px" }} onClick={() => click_tab("立即录波")}>立即录波</div>
                    <div className={`${lessModule["header-tab__btn"]}`} style={{ color: tabName === "预约录波" ? "#FFFFFF" : "#B8D6E6", backgroundColor: tabName === "预约录波" ? "rgba(23,161,230,0.5)" : "rgba(23,161,230,0.1)", borderWidth: tabName === "预约录波" ? "0 0 1px 0" : "1px", borderColor: tabName === "预约录波" ? "#17A1E6" : "rgba(23,161,230,0.3)", padding: tabName === "预约录波" ? "10px 8px 10px 7px" : "10px 7px 10px 8px" }} onClick={() => click_tab("预约录波")}>预约录波</div>
                </div>
                <img className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-header__closeImage"]}`} src={modalCloseImage} onClick={() => click_closeModal()} />
            </div>
            <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponent-homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent__main"]}`}>
                {
                    step === 0 && <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-main__step0"]}`}>
                        <div className={`${lessModule["main-step0__left"]}`}>
                            <div>录波范围</div>
                            <div className={`${lessModule["step0-left__card"]}`}>
                                {
                                    treeList.length > 0 && <Tree
                                        checkable
                                        defaultExpandAll
                                        checkedKeys={selectedList}
                                        treeData={treeList}
                                        onCheck={check_tree}
                                    />
                                }
                            </div>
                        </div>
                        <div className={`${lessModule["main-step0__right"]}`}>
                            <div>已选（{selectedList.length}）</div>
                            <div className={`${lessModule["step0-right__card"]}`}>
                                {
                                    selectedList.map((item, idx) => {
                                        return (
                                            <div className={`${lessModule["right-card__tag"]}`}>
                                                <div>{`${item.toString().split("%@)")[3]}-${item.toString().split("%@)")[4]}`}</div>
                                                <div className={`${lessModule["card-tag__clear"]}`} onClick={() => click_tagClear(idx)}>x</div>
                                            </div>
                                        )
                                    })
                                }
                            </div>
                        </div>
                    </div>
                }
                {
                    step === 1 && <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-main__step1"]}`}>
                        <div>开始时间</div>
                        <div className={`${lessModule["main-step1__row"]}`}>
                            <DatePicker popupClassName="row-datePicker__pickerDropdown" showTime value={dayjs(startTime)} allowClear={false} onChange={change_startTime} />
                            <div className={`${lessModule["step1-row__divide"]}`}>-</div>
                            <InputNumber addonAfter="ms" placeholder="请输入" />
                        </div>
                        <div>录波时长</div>
                        <Radio.Group onChange={change_duration}>
                            <Radio value={0.4}>0.4 s</Radio>
                            <Radio value={1}>1 s</Radio>
                            <Radio value={20}>20 s</Radio>
                            <Radio value={60}>60 s</Radio>
                        </Radio.Group>
                    </div>
                }
            </div>
            <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponent-homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent__footer"]}`}>
                {
                    !(tabName === "预约录波" && step === 1) && <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-footer__btn"]} ${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-footer__closeBtn"]}`} onClick={() => click_closeModal()}>取 消</div>
                }
                {
                    tabName === "预约录波" && step === 1 && <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-footer__btn"]} ${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-footer__closeBtn"]}`} onClick={() => click_lastStep()}>上一步</div>
                }
                {
                    !(tabName === "预约录波" && step === 0) && <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-footer__btn"]} ${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-footer__submitBtn"]}`} onClick={() => click_submitModal()}>确 定</div>
                }
                {
                    tabName === "预约录波" && step === 0 && <div className={`${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-footer__btn"]} ${lessModule["homePageDataManagementPageHeaderMenuSearchComponentModalContentComponent-footer__submitBtn"]}`} onClick={() => click_nextStep()}>下一步</div>
                }
            </div>
        </div>
    )
}

// 主页-数据管理页面-头部菜单查询组件
const HomePage_DataManagementPage_HeaderMenuSearchComponent: React.FC = () => {
    const location = useLocation()
    let [isSearchShow, setIsSearchShow] = useState<boolean>(false)
    const [isModal, setIsModal] = useState<boolean>(false)
    const [isDrawer, setIsDrawer] = useState<boolean>(false)
    const [isPrepareCloseModal, setIsPrepareCloseModal] = useState<boolean>(false)
    const [isPrepareCloseDrawer, setIsPrepareCloseDrawer] = useState<boolean>(false)
    const freewayList = [{ label: "全部" }, { label: "德会高速" }, { label: "绵九高速" }]
    let [freewayName, setFreewayName] = useState<string>("")
    let [siteList, setSiteList] = useState<Array<object>>([])
    let [siteName, setSiteName] = useState<string>("")


    const click_cancel = () => {
        setIsSearchShow(false)
    }
    const emit_tableSearchConditionData = ()=>{
        setTimeout(() => {
            $eventBus.emit("eventBus_tableSearchConditionData", { line: freewayName, station: siteName })
           });
    }
    const click_search = () => {
        isSearchShow || location.pathname.split("/")[3] === "historicalCurve"  ? emit_tableSearchConditionData() : setIsSearchShow(true)
    }
    const click_addRecordingData = () => {
        setIsModal(true)
    }
    const click_addDataExport = () => {
        setIsDrawer(true)
    }

    const change_freewayName = (value: string) => {
        freewayName = value
        setFreewayName(freewayName)
        init_siteList()
    }

    const change_siteName = (value: string) => {
        setSiteName(value)
    }
    const get_isModalClose = () => {
        setIsPrepareCloseModal(true)
        setTimeout(() => {
            setIsModal(false)
            setIsPrepareCloseModal(false)
        }, 300);
    }
    const get_isDrawerClose = () => {
        setIsPrepareCloseDrawer(true)
        setTimeout(() => {
            setIsDrawer(false)
            setIsPrepareCloseDrawer(false)
        }, 300);
    }
    const init_siteList = () => {

        siteList = [{label:"全部"}].concat(freewayName === "全部" ? JSON.parse(sessionStorage.homePage_freewayList)?.[0]?.["options"].concat(JSON.parse(sessionStorage.homePage_freewayList)?.[1]?.["options"]) : JSON.parse(sessionStorage.homePage_freewayList).find((item: object) => item["label"] === freewayName)?.["options"])
        siteName = siteList?.[0]?.["label"]
        setSiteList([...siteList])
        setSiteName(siteName)
    }
    useEffect(()=>{
        isSearchShow= false
        freewayName = '全部'
        setIsSearchShow(isSearchShow)
        setFreewayName(freewayName)
        init_siteList()
        emit_tableSearchConditionData()
    },[location])
    return (
        <div className={`${lessModule["homePageDataManagementPage-headerMenu__homePageDataManagementPageHeaderMenuSearchComponent"]}`}>
            {
                isSearchShow && <>

                    <div className={`${lessModule["headerMenu-homePageDataManagementPageHeaderMenuSearchComponent__hiddenBlock"]}`}>
                        <div className={`${lessModule["homePageDataManagementPageHeaderMenuTabComponent-hiddenBlock__conditionBox"]}`}>
                            <span>线路：</span>
                            <Select
                                className={`${lessModule["hiddenBlock-conditionBox__freewaySelect"]}`}
                                value={freewayName}
                                onChange={change_freewayName}
                                options={freewayList}
                                fieldNames={{ value: "label" }}
                            />
                        </div>
                        {
                            ["siteAccount"].includes(location.pathname.split("/")[3]) && <div className={`${lessModule["homePageDataManagementPageHeaderMenuTabComponent-hiddenBlock__conditionBox"]}`}>
                                <span>站点：</span>
                                <Select
                                    className={`${lessModule["hiddenBlock-conditionBox__siteSelect"]}`}
                                    value={siteName}
                                    onChange={change_siteName}
                                    options={siteList}
                                    fieldNames={{ value: "label" }}
                                />
                            </div>
                        }
                        <div className={`${lessModule["headerMenu-homePageDataManagementPageHeaderMenuTabComponent__btn"]} ${lessModule["homePageDataManagementPageHeaderMenuTabComponent-hiddenBlock__cancelBtn"]}`} onClick={() => click_cancel()}>取消</div>
                    </div>

                    <>

                    </>
                </>
            }
            {
                ["siteAccount", "historicalCurve", "eventStatistics"].includes(location.pathname.split("/")[3]) && <div className={`${lessModule["headerMenu-homePageDataManagementPageHeaderMenuTabComponent__btn"]} ${lessModule["headerMenu-homePageDataManagementPageHeaderMenuTabComponent__searchBtn"]}`} onClick={() => click_search()}>查询</div>
            }
            {
                ["recordingData"].includes(location.pathname.split("/")[3]) && <div className={`${lessModule["headerMenu-homePageDataManagementPageHeaderMenuTabComponent__btn"]} ${lessModule["headerMenu-homePageDataManagementPageHeaderMenuTabComponent__searchBtn"]}`} onClick={() => click_addRecordingData()}>新建录波</div>
            }
            {
                ["dataExport"].includes(location.pathname.split("/")[3]) && <div className={`${lessModule["headerMenu-homePageDataManagementPageHeaderMenuTabComponent__btn"]} ${lessModule["headerMenu-homePageDataManagementPageHeaderMenuTabComponent__searchBtn"]}`} onClick={() => click_addDataExport()}>新建</div>
            }
            <>
                {
                    isModal && <HomePage_ModalComponent isPrepareCloseModal={isPrepareCloseModal} get_isModalClose={get_isModalClose}
                        ModalContentComponents={<HomePage_DataManagementPage_HeaderMenuSearchComponent_ModalContentComponent get_isModalClose={get_isModalClose} />} />
                }
            </>
            <>
                {
                    isDrawer && <HomePage_DrawerComponent isPrepareCloseDrawer={isPrepareCloseDrawer} get_isDrawerClose={get_isDrawerClose}
                        DrawerContentComponents={<HomePage_DataManagementPage_HeaderMenuSearchComponent_DrawerContentComponent get_isDrawerClose={get_isDrawerClose} />} />
                }
            </>
        </div>
    )
}

// 主页-数据管理页面
const HomePage_DataManagementPage: React.FC = () => {
    return (
        <div className={`${lessModule["homePageDataManagementPage"]}`}>
            <header className={`${lessModule["homePageDataManagementPage-headerMenu"]}`}>
                <HomePage_DataManagementPage_HeaderMenuTabComponent />
                <HomePage_DataManagementPage_HeaderMenuSearchComponent />
            </header>
            <Outlet />
        </div>
    )
}

export default HomePage_DataManagementPage